package com.lyp.activitys;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.lyp.jsonbean.ChengdanBean;
import com.lyp.jsonbean.IndoorTaskDetailsBean;
import com.lyp.jsonbean.MNoyuyueBean;
import com.tjl.yangxixis.R;
import com.tjl.yangxixis.activity.SignActivity;
import com.tjl.yangxixis.api.YangxixiApi;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class IndoorMyNoyuyueActivity extends Activity implements View.OnClickListener {

    private TextView tv_cheng, tv_yuyue;
    private TextView mMoreinformation, mPackup, mQiandao;
    private ImageView mBack, mServicereport, mExaminingreport, mCallPhone;

    private RecyclerView mRecyclerView0;
    private LinearLayoutManager mLinearLayoutManager0;
    private IndoorMyNoyuyueActivity.GalleryAdapter mAdapter0;
    private ArrayList<String> mSelectPath0 = new ArrayList<>();
    private ArrayList<String> mSelectPath = new ArrayList<>();

    private TextView mName, mPhone, mAddress, mSpot, mMianji, mOrder, mTime;

    private List<IndoorTaskDetailsBean.DataBean> mList = new ArrayList<>();

    private MNoyuyueBean.DataBean bean;

    private TextView mTvDetailTime, mTvDetailRemark1,mInformation;

    private LinearLayout mMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_indoor_details_clue);
        init();
    }

    private void init() {
        bean = (MNoyuyueBean.DataBean) getIntent().getExtras().get("databean");
        mBack = (ImageView) findViewById(R.id.indoor_back);
        tv_cheng = (TextView) findViewById(R.id.tv_cheng);
        tv_yuyue = (TextView) findViewById(R.id.tv_yuyue);
        mQiandao = (TextView) findViewById(R.id.tv_qiandao);
        mCallPhone = (ImageView) findViewById(R.id.iv_indoor_phone);

        mInformation = (TextView) findViewById(R.id.indoor_more_information);
        mPackup = (TextView) findViewById(R.id.indoor_pack_up);
        mServicereport = (ImageView) findViewById(R.id.indoor_service_report);
        mExaminingreport = (ImageView) findViewById(R.id.indoor_examiningreport);

        mTvDetailTime = (TextView) findViewById(R.id.indoor_yuyue);
        mTvDetailRemark1 = (TextView) findViewById(R.id.tv_indoor_remark);
        mMessage = (LinearLayout) findViewById(R.id.ll_indoor_message);

        tv_cheng.setOnClickListener(this);
        mPackup.setOnClickListener(this);//收起
        mServicereport.setOnClickListener(this);
        mExaminingreport.setOnClickListener(this);
        mQiandao.setOnClickListener(this);
        mCallPhone.setOnClickListener(this);
        mBack.setOnClickListener(this);
        tv_yuyue.setOnClickListener(this);
        mInformation.setOnClickListener(this);

        // 服务报告图片
        mRecyclerView0 = (RecyclerView) findViewById(R.id.rv_indoor_service_report);
        mLinearLayoutManager0 = new LinearLayoutManager(this);
        mLinearLayoutManager0.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView0.setLayoutManager(mLinearLayoutManager0);
        mAdapter0 = new IndoorMyNoyuyueActivity.GalleryAdapter(this, mSelectPath0);
        mRecyclerView0.setAdapter(mAdapter0);

        mName = (TextView) findViewById(R.id.indoor_name);
        mPhone = (TextView) findViewById(R.id.indoor_phone);
        mAddress = (TextView) findViewById(R.id.indoor_address);
        mSpot = (TextView) findViewById(R.id.indoor_spot);
        mMianji = (TextView) findViewById(R.id.indoor_mianji);
        mOrder = (TextView) findViewById(R.id.indoor_order);
        mTime = (TextView) findViewById(R.id.indoor_time);

        indoordetailsclue(bean.getO_id());
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.indoor_back:
                finish();
                break;
            case R.id.tv_cheng:
                if (mSelectPath0.size() <= 0) {
                    ToastUtils.showShortSafe("请选择服务报告");
                } else {
                    try {
                        RequestBody o_id = RequestBody.create(
                                MediaType.parse("multipart/form-data"), bean.getO_id());
                        // 上传文件
                        uploadFile(o_id, pathToFile(mSelectPath0), pathToFile(mSelectPath));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;

            //更多信息
            case R.id.indoor_more_information:
                mPackup.setVisibility(View.VISIBLE);
                mInformation.setVisibility(View.GONE);
                mMessage.setVisibility(View.VISIBLE);
                break;
            //收起
            case R.id.indoor_pack_up:
                mInformation.setVisibility(View.VISIBLE);
                mPackup.setVisibility(View.GONE);
                mMessage.setVisibility(View.GONE);
                break;
            //添加服务报告
            case R.id.indoor_service_report:
                MultiImageSelector.create(this)
                        .showCamera(true) // 是否显示相机. 默认为显示
                        .count(9) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                        .multi() // 多选模式, 默认模式;
                        .origin(mSelectPath) // 默认已选择图片. 只有在选择模式为多选时有效
                        .start(this, 0x100);
                break;
            //签到
            case R.id.tv_qiandao:
                Intent qiandao = new Intent(this, SignActivity.class);
                Bundle bundles = new Bundle();
                bundles.putSerializable("databean",bean);
                qiandao.putExtras(bundles);
                startActivity(qiandao);
                break;
            //拨打电话
            case R.id.iv_indoor_phone:
                // 判断环境兼容，检查自己的权限，是否被同意
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
                    //如果不同意，就去请求权限   参数1：上下文，2：权限，3：请求码
                    ActivityCompat.requestPermissions(this,new String []{Manifest.permission.CALL_PHONE},1);
                }else {
                    //同意就拨打
                    final String phone = mPhone.getText().toString();
                    new MaterialDialog.Builder(this)
                            .title("拨打电话")
                            .content(phone)
                            .positiveText("拨打")
                            .negativeText("取消")
                            .onAny(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    switch (which.toString()) {
                                        case "POSITIVE":
                                            PhoneUtils.call(phone);
                                            break;

                                        case "NEGATIVE":
                                            dialog.dismiss();
                                            break;
                                    }
                                }
                            })
                            .show();
                }
                break;
            //预约时间
            case R.id.tv_yuyue:
                Intent intentyuyue = new Intent(this, YuyueNoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("databean", bean);
                intentyuyue.putExtras(bundle);
                startActivityForResult(intentyuyue, 0x300);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x100) {
                mSelectPath0.clear();
                mSelectPath0.addAll(data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT));
                mAdapter0.notifyDataSetChanged();
            }
        } else if (requestCode == 0x300) {
            String time = data.getStringExtra("time");
            String bz = data.getStringExtra("bz");
            mTvDetailTime.setText(time);
            mTvDetailRemark1.setText(bz);

            setResult(RESULT_OK, null);
        }

    }


    /**
     * 将 Path 转化成 File
     */
    public static List<File> pathToFile(List<String> pathList) {
        List<File> list = new ArrayList<>();
        for (int i = 0; i < pathList.size(); i++) {
            String path = pathList.get(i);
            list.add(FileUtils.getFileByPath(path));
        }
        return list;
    }

    /**
     * 将 File 转化成 RequestBody
     */
    public static Map<String, RequestBody> fileToRequestBody(int index, String name, List<File> fileList) {
        Map<String, RequestBody> paramsMap = new HashMap<>();
        for (int i = index; i < index + fileList.size(); i++) {
            File file = fileList.get(i - index);
            RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            paramsMap.put(name + "\"; filename=\"" + index + ".png", fileBody);
        }
        return paramsMap;
    }

    // 上传文件
    public void uploadFile(RequestBody o_id, List<File> fileList0, List<File> fileList) throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        YangxixiApi api = retrofit.create(YangxixiApi.class);
        Call<ChengdanBean> call = api.uploadFile(o_id, fileToRequestBody(1001, "detection[]", fileList0), fileToRequestBody(2001, null, fileList));
        call.enqueue(new Callback<ChengdanBean>() {
            @Override
            public void onResponse(Call<ChengdanBean> call, final Response<ChengdanBean> response) {
                if (response.body().getResult() == 1) {
                    ToastUtils.showShort(response.body().getMessage());
                    new MaterialDialog.Builder(IndoorMyNoyuyueActivity.this)
                            .content("恭喜你!该订单已成单！")
                            .positiveText("确定")
                            .canceledOnTouchOutside(false)
                            .cancelable(false)
                            .onPositive(new MaterialDialog.SingleButtonCallback(){
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    setResult(400);
                                    finish();
                                }
                            })
                            .show();
                } else {
                    ToastUtils.showShort(response.body().getMessage() + response.body().getResult());
                }
            }

            @Override
            public void onFailure(Call<ChengdanBean> call, Throwable t) {
                ToastUtils.showShortSafe("上传失败");
            }
        });
    }

    public class GalleryAdapter extends RecyclerView.Adapter<IndoorMyNoyuyueActivity.GalleryAdapter.ViewHolder> {

        private LayoutInflater mInflater;
        private ArrayList<String> mDatas;

        GalleryAdapter(Context context, ArrayList<String> datats) {
            mInflater = LayoutInflater.from(context);
            mDatas = datats;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public ViewHolder(View arg0) {
                super(arg0);
            }

            ImageView mImg;
        }

        @Override
        public int getItemCount() {
            return mDatas.size();
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public IndoorMyNoyuyueActivity.GalleryAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
            View view = mInflater.inflate(R.layout.item_rv,
                    viewGroup, false);
            IndoorMyNoyuyueActivity.GalleryAdapter.ViewHolder viewHolder = new IndoorMyNoyuyueActivity.GalleryAdapter.ViewHolder(view);

            viewHolder.mImg = (ImageView) view
                    .findViewById(R.id.item_rv_iv);
            return viewHolder;
        }

        /**
         * 设置值
         */
        @Override
        public void onBindViewHolder(final IndoorMyNoyuyueActivity.GalleryAdapter.ViewHolder viewHolder, int i) {
//            viewHolder.mImg.setImageBitmap(ImageUtils.getBitmap(mDatas.get(i)));
            File file = new File(mDatas.get(i));
            //加载图片
            Glide.with(IndoorMyNoyuyueActivity.this).load(file).into(viewHolder.mImg);
        }
    }


    //详情
    public void indoordetailsclue(String o_id) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YangxixiApi.APP_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        YangxixiApi api = retrofit.create(YangxixiApi.class);
        Call<IndoorTaskDetailsBean> call = api.getInoorTaskDetails(o_id);
        call.enqueue(new Callback<IndoorTaskDetailsBean>() {
            @Override
            public void onResponse(Call<IndoorTaskDetailsBean> call, final Response<IndoorTaskDetailsBean> response) {
                if (response.body().getResult() == 1) {
                    IndoorMyNoyuyueActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mList.addAll(response.body().getData());
                            mName.setText(mList.get(0).getUser_name());
                            mPhone.setText(mList.get(0).getU_phone());
                            mAddress.setText(mList.get(0).getU_addres());
                            mSpot.setText(mList.get(0).getPoint_position());
                            mMianji.setText(mList.get(0).getCovered_area());
                            mOrder.setText(mList.get(0).getOrder_number());
                            mTime.setText(mList.get(0).getPay_time());
                            if (bean.getSubscriber_type().equals("1")) {
                                mTvDetailTime.setText(mList.get(0).getSubscriber_time());
                                mTvDetailRemark1.setText(mList.get(0).getNote());
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<IndoorTaskDetailsBean> call, Throwable t) {
                ToastUtils.showShort(t.getMessage());
            }
        });
    }
}